//index.js
//获取应用实例
const app = getApp()

const fetchSev = require("../../utils/util.js").fetchSev;
const getCateUrl = require("../../config.js").getCateUrl;
const getSkusUrl = require("../../config.js").getSkusUrl;


let tabArr = [];

Page({
  data: {
    navData: [],     // 品类列表
    currentNav: {},  // 当前被点击的品类
    currentTitle: '新/品/推/荐',

    skuList: [],     // sku列表
    noGoodShow: false,

    searchText: "",  // 搜索关键字

    filter: {
      // q_cate_id: "",
      // q_keyword: "",
      // q_max_weight: "",
      // q_min_weight: "",
      // pagesize: 12,
      // page: 1,

      department:'',
      cate_id:'',
      spu_id: '',
      craft: '',
      sku_name: '',
      max_weight: '',
      min_weight: '',
      order_by: '',    // weights-up / weights-down
      page: 1,
      pagesize: 15
    }
  },

  onLoad: function () {
    const that = this;
    app.loginCallback = () => {
      that._init();
    }
  },

  onShow: function () {
    this._init();
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    wx.showToast({
      title: '正在刷新',
      icon: 'loading'
    });
    this._init();
  },
  // 触底加载
  onReachBottom: function () {
    let page = parseInt(this.data.filter.page);
    page = page + 1;
    this._updateFilter('page', page);
    this._sku(this.data.filter);
  },

  // 首页初始化
  _init: function () {
    console.log('页面刷新');
    // 重置数据
    this._reset();

    // 初始化品类导航
    fetchSev(getCateUrl, "GET", {}, function (res) {
      let cates = res.data;
      delete cates['total'];  // 删除total字段
      for (let cate in cates) {
        // 设置品类icon
        if (!cates[cate].image || cates[cate].image.length < 1){
          cates[cate].src = "../../images/cate/" + "1000009" + ".png";
        } else {
          cates[cate].src = `http://${cates[cate].image[0]['domain']}/${cates[cate].image[0][100]}`;          
        }
      }
      this.setData({ navData: cates });
      console.log('品类', this.data.navData);
    }.bind(this));

    // 初始化“新品推荐”
    const initFilter = this.data.filter;
    this._sku(initFilter);
  },

  // data重置
  _reset: function() {    
    this.setData({ searchText: '' });
    this.setData({ currentNav: {} });
    this.setData({ noGoodShow: false });
    // 重置skuList
    this.setData({ skuList: [] });
    // 重置filter.page
    this._updateFilter('page', 1);
  },

  

  /**
   * 功能一：搜索
   */
  // 搜索按钮
  _inputChange(e) {
    this.setData({
      searchText: e.detail.value
    });
  },
  _searchClick: function (e) {
    console.log(this.data.searchText);
    if (this.data.searchText == "") {
      wx.showToast({
        title: '搜索内容不能为空',
        icon: 'none',
        duration: 1000
      })
    } else {
      console.log('跳转');
      app.globalData.searchText = this.data.searchText;
      // 重置filter页面中的筛选条件
      for (let k in app.globalData.filter) {
        app.globalData.filter[k] = '';
      }
      wx.navigateTo({
        url: '../search/search'
      })
    }
    // console.log(e);
  },

  /**
   * 功能二：分类导航
   */
  // 分类导航点击
  _navClick(e) {
    const nav = e.currentTarget.dataset.nav;
    console.log('当前品类', nav);
    this.setData({currentNav: nav});
    this.setData({ currentTitle: nav.name.split('').join(' / ')});
    this._updateFilter('page', 1);
    this._updateFilter('cate_id', nav.id);
    // 重置skuList
    this.setData({skuList: []});
    this.setData({ searchText: '' });
    this.setData({ noGoodShow: false });
    // 搜索skuList
    this._sku(this.data.filter);
  },

  /**
   * 功能三：sku选货
   */
  // 更新filter
  _updateFilter: function (k, v) {
    let filter = this.data.filter;
    filter[k] = v;
    this.setData({ filter: filter });
  },
  // 选货
  _sku: function (filter) {
    // 显示加载中
    wx.showLoading({
      title: '加载中',
    });
    // 选货  pagesize,page,q_keyword(关键字),q_cate_id(品类id),q_max_weight(最大克重),q_min_weight(最小克重)  order_by(max_weight:克重范围降序,min_weight(克重范围升序))
    let skuList = this.data.skuList;
    console.log('filter', filter);
    fetchSev(getSkusUrl, "GET", filter, function (data) {
      console.log('小码列表', data);
      if(!data || data.length == 0) {
        wx.showToast({
          title: '数据已加载完毕',
          icon: 'none'
        });
        return;
      }
      // 提示上拉加载已完毕
      // 追加
      skuList = skuList.concat(data || []);
      // 没有商品
      if (skuList.length == 0) {
        this.setData({ noGoodShow: true});
      }
      this.setData({skuList: skuList});
      // 停止下拉刷新
      wx.stopPullDownRefresh();
      // 隐藏loading
      wx.hideLoading();
    }.bind(this));
  },
  // 点击sku产品
  _skuClick: function (e) {
    const sku = e.currentTarget.dataset.sku;
    console.log(sku);
    app.globalData.currentSku = sku;
    wx.navigateTo({
      url: '../detail/detail'
    })

  },

})
